package com.imooc.dianping.controller.admin;

import com.imooc.dianping.common.AdminPermission;
import com.imooc.dianping.common.BusinessException;
import com.imooc.dianping.common.CommonUtil;
import com.imooc.dianping.common.EmBusinessError;
import com.imooc.dianping.service.CategoryService;
import com.imooc.dianping.service.SellerService;
import com.imooc.dianping.service.ShopService;
import com.imooc.dianping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("/admin/admin")
public class AdminController {

    public static final String CURRENT_ADMIN_SESSION = "currentAdminSession";

    @Value("${admin.email}")
    private String email;
    @Value("${admin.encryptPassword}")
    private String encryptPassword;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private UserService userService;
    @Autowired
    private SellerService sellerService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ShopService shopService;

    @RequestMapping("/index")
    @AdminPermission
    public String index(Model model) {
        model.addAttribute("CONTROLLER_NAME","admin");
        model.addAttribute("ACTION_NAME","index");
        model.addAttribute("userCount",userService.count());
        model.addAttribute("sellerCount",sellerService.count());
        model.addAttribute("categoryCount",categoryService.count());
        model.addAttribute("shopCount",shopService.count());
        return "/admin/admin/index";
    }

    @RequestMapping("/loginpage")
    public String loginPage() {
        return "/admin/admin/login";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("email") String email, @RequestParam("password") String password) throws NoSuchAlgorithmException {
        if (StringUtils.isEmpty(email)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "用户名为空");
        }
        if (email.equals(this.email) && encryptPassword.equals(CommonUtil.encodeByMd5(password))) {
            httpServletRequest.getSession().setAttribute(CURRENT_ADMIN_SESSION, email);
            return "redirect:/admin/admin/index";
        } else {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "用户名密码错误");
        }
    }


}
